﻿using System;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using TSB.SharePointUrlShortener.DAL;

namespace TSB.SharePointUrlShortener.Layouts.TSB.SharePointUrlShortener
{
    public class Service : IHttpHandler
    {
        public bool IsReusable
        {          
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var serializer = new JavaScriptSerializer();
            var sbJsonResults = new StringBuilder();

            var shortcode = context.Request.QueryString["shortcode"] ?? string.Empty;

            serializer.Serialize(CheckExistingShortcode(shortcode), sbJsonResults);
            context.Response.Clear();
            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.Write(sbJsonResults.ToString());
        }


        JsonExists CheckExistingShortcode(string shortcode)
        {
            var response =  new JsonExists();
            var urlShortenerRepository = new UrlShortenerRepository();

            var temp = string.Empty;
            response.DoesExist = urlShortenerRepository.CheckShortcodeExists(shortcode, out temp);
            response.ExistingValue = temp;
            return response;
        }
    }
}
